﻿@using System.Collections
@using CNav.Domain
@using CNav.Domain.Admin
@model CNav.Model.EnquiryModel
@{
    ViewBag.Title = "New Enquiry";
}

@using (Html.BeginForm("NewEnquiry", "Enquiry", FormMethod.Post, new { name = "frmMain", id = "frmMain" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div id="consumerAccordion">
        @* ============== Consumer Details ================ *@
        <h2>Consumer Profile</h2>
        <hr>
        <div class="section-data">

            @Html.HiddenFor(m => m.ConsumerID)

            <div>
                <div>
                    <label class="small">Search</label>
                    @Html.TextBoxFor(m => m.SearchModel.SearchText)
                    &nbsp;&nbsp; In &nbsp; @Html.DropDownListFor(model => model.SearchModel.SearchType, new SelectList(Model.SearchModel.SearchTypes))
                    <input type="button" value="Search" id="search" />
                    <input type="button" value="Add New" id="addConsumer" />
                </div>
                <div id="searchMessage">
                    Consumer not found, Please search again.
                </div>
                <div id="searchPanel">
                    <label>&nbsp;</label><div>
                        <select size="3" id="listBox" class="consumerSearchList"></select>
                        <div id="consumerDetail" class="consumerSearchList"></div>
                    </div>
                </div>
            </div>
        </div>

        @* ============== Business Details ================ *@
        <h2>Business Profile</h2>
        <hr>
        <div>
            <ol>
                <li>
                    @Html.Label("Business")
                    @Model.BusinessModel.BusinessName
                </li>
                <li>
                    @Html.LabelFor(m => m.BusinessModel.PhoneNumber)
                    @Model.BusinessModel.PhoneNumber
                </li>
                <li>
                    @Html.LabelFor(m => m.BusinessModel.Email)
                    @Model.BusinessModel.Email
                </li>
                <li>
                    <label>Address</label>
                    @{
    if (Model.BusinessModel.Address == null)
    {
                        <span style="color: red;">Business address not updated.</span>
    }
    else
    {
                        @Model.BusinessModel.Address
    }
                    }
                </li>
            </ol>
        </div>

        @* ============== Complain Details ================ *@
        <h2>Complain Details</h2>
        <hr>
        <div>
            <ol>
                <li>
                    @Html.Label("Product")
                    @Html.DropDownListFor(model => model.ProductID, new SelectList(ViewBag.ProductList, "ID", "Name")) &nbsp;<span id="product">&nbsp;</span>
                    <br />
                    @Html.ValidationMessageFor(model => model.ProductID)
                </li>
                <li>
                    @Html.Label("Complaint Type")
                    @Html.DropDownListFor(model => model.ComplaintType, new SelectList(ViewBag.ComplaintTypeList, "ID", "Code")) &nbsp;<span id="complaintDescription">&nbsp;</span>
                    <br />
                    @Html.ValidationMessageFor(model => model.ComplaintType)
                </li>
                <li>
                    @Html.Label("Description")
                    @Html.TextAreaFor(m => m.Description, new { rows = "5" })
                </li>
            </ol>
        </div>

        @{
    if (Model.RenderControlListModel.Controls != null && Model.RenderControlListModel.Controls.Any())
    {
@* ============== Consumer Details ================ *@
            <h2>More Information</h2>
            <hr>
            <div>
                <ul>
                    @{ Html.RenderPartial("RenderView", Model.RenderControlListModel); }
                </ul>
            </div>
    }
        }

    </div>

    <div>
        <ol>
            <li class="liCentre">
                <input type="submit" value="New Enquiry" id="editButton" />
                <input type="button" value="Cancel" id="cancelButton" />
            </li>
        </ol>
    </div>
    <br />
    <br />
}
<div id="dialogForm" title="Create new consumer">
    <form id="consumerForm">
        <div id="container"></div>
    </form>
</div>
<script>

    var cc = new CaseCentre();

    function OnComplaintTypeSelected() {
        var id = $("#ComplaintType").val();
        if (id != 0) {
            var cmd = '@Url.Content("~/api/ComplaintType/Get/")' + id;
            cc.OnCommand(cmd, null, 'json', 'GET', OnComplaintTypeResult, null);
        }
    }

    function OnComplaintTypeResult(result) {
        $("#complaintDescription").html(result.Description);
    }

    function OnProductSelected() {

        var id = $("#ProductID").val();
        if (id != 0) {
            var cmd = '@Url.Content("~/api/Product/Get/")' + id;
            cc.OnCommand(cmd, null, 'json', 'GET', OnProductResult, null);
        }
    }

    function OnProductResult(result) {

        if (result.Category != null) {
            var businessContact = "Category:&nbsp;&nbsp;" + result.Category
          + ",  " + result.SubCategory + " &nbsp; " + result.Description;
            $("#product").html(businessContact);
        }
    }

    var SearchResult = null;

    function onConsumerSearchResult(result) {

        SearchResult = result;

        var listBox = $('#listBox');
        var searchPanel = $("#searchPanel");

        listBox.find('option').remove().end();

        $(result).each(function (r) {

            var rec = result[r];
            var li = $('<option></option>');
            li.val(rec.ID);
            var lineText = '';
            if (rec.Title)
                lineText += rec.Title;

            if (rec.FirstName)
                lineText += ' ' + rec.FirstName;

            if (rec.LastName)
                lineText += ' ' + rec.LastName;

            if (rec.Email)
                lineText += ' (' + rec.Email + ')';

            li.text(lineText);
            li.appendTo(listBox);
        });

        if (result.length > 0) {
            searchPanel.show();
            $('#searchMessage').hide();
        }
        else {
            $('#searchMessage').show();
            searchPanel.hide();
        }
    };

    $('#listBox').change(function () {
        var id = $(this).val();
        var consumer = $.grep(SearchResult, function (e) { return e.ID == id; })[0];

        var consumerText = consumer.Title + ' ' + consumer.FirstName + ' ' + consumer.MiddleName + ' ' + consumer.LastName + '<br/>';
        consumerText += 'Birth Date: ' + consumer.BirthDate.replace('00:00:00', '') + '<br/>';
        consumerText += 'Email: ' + consumer.Email + '<br/>';
        consumerText += 'PhoneNumber: ' + consumer.PhoneNumber + '<br/>';

        $('#ConsumerID').val(consumer.ID);

        $('#consumerDetail').html(consumerText);

    });

    function hidePanel(err) {
        var searchPanel = $("#searchPanel");
        searchPanel.hide();
    }

    function onError(err) {
        alert('Error :  ' + JSON.stringify(err));
    }

    $(function () {

        cc.Datepicker("#ConsumerModel_BirthDate");
        cc.BindCancel('#cancelButton', '@Url.Content("~/Enquiry/")');
        //cc.Accordion('#consumerAccordion');
        $('#SearchModel_SearchText').css('width', '140px');
        $('#SearchModel_SearchType').css('width', '140px');

        var searchPanel = $("#searchPanel");
        searchPanel.hide();
        $('#searchMessage').hide();

        cc.BindSearch('#search', '#SearchModel_SearchText', '#SearchModel_SearchType', '@Url.Content("~/api/Consumer/Search/")', onConsumerSearchResult, hidePanel);

        $('#SearchModel_SearchText').keyup(function () {
            if ($(this).val().length == 0) $("#searchPanel").hide();
        });

        var isDatepicker = false;

        $('#SearchModel_SearchType').change(function () {
            var selected = $(this).val();
            var searchBox = $('#SearchModel_SearchText');

            if (selected == 'BirthDate') {
                cc.Datepicker('#SearchModel_SearchText');
                searchBox.val('');
                isDatepicker = true;
            }
            else {
                if (isDatepicker) {
                    searchBox.datepicker("destroy");
                    searchBox.val('');
                    isDatepicker = false;
                }
            }
        });

        var modelDialog = $("#dialogForm");
        modelDialog.hide();

        var container = $("#container");
        $('#addConsumer').click(function () {

            cc.OnCommand('@Url.Content("~/Consumer/Create")', null,
               null,
               'GET',
               function (result) {

                   container.html(result);
                   modelDialog.dialog({
                       show: "slow",
                       height: 500,
                       width: 500,
                       buttons: {
                           "Create an account": function () {
                               cc.OnCommand('@Url.Content("~/Consumer/Create/")',
                                   $('#consumerForm').serialize(),
                                   'html',
                                   'POST',
                                   function (response) {

                                       if (response == 'OK') {
                                           // Set search text and click button
                                           $("#SearchModel_SearchText").val($("#FirstName").val());
                                           $("#consumerDetail").html('');
                                           $("#search").click();
                                           modelDialog.dialog("close");
                                       }
                                       else {
                                           container.html(response);
                                       }
                                   },
                                   onError);
                           },
                           Cancel: function () {
                               $(this).dialog("close");
                           }
                       }
                   });
               },
               onError);
        });


        $("#ProductID").change(OnProductSelected);

        $("#ComplaintType").change(OnComplaintTypeSelected);

        OnProductSelected();
        OnComplaintTypeSelected();

    });
</script>
